const createError = require("http-errors")

function success(res, message, data = {}, code = 200) {
    return res.status(code).json({
        status: true,
        message,
        data
    })
}

function failure(res, error) {
    let statusCode;
    let errors;

    if(error.name === "SequelizeValidationError") {
        statusCode = 400
        errors = error.errors.map(e => e.message)
    } else if(error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
        statusCode = 401
        errors = "您提交的 token 错误或已过期"
    } else if(error instanceof createError.HttpError) {
        statusCode = error.status
        errors = error.message
    } else {
        statusCode = 500
        errors = "服务器错误"
    }
    res.status(statusCode).json({
        status: false,
        message: `请求失败: ${error.name}`,
        errors: Array.isArray(errors) ? errors : [errors]
    })
}

module.exports = {
    success,
    failure
}